/*
 *  Property Mapper, simple automatic GUI generator for JavaBeans using annotations.
 *  Copyright (C) 2008 Jon Lennersten, Johan Hedin
 *
 *  This file is part of Property Mapper.
 *
 *  Property Mapper is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Property Mapper is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Property Mapper.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.mawell.common.propertymapperswing;

import javax.swing.*;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;

/**
 * @version $Revision: 1.2 $
 */

public class IntField extends JTextField {

        public IntField(int cols) {
            super(cols);
        }

        public IntField(String text) {
            super(text);
        }

        public IntField(String text, int cols) {
            super(text, cols);
        }

        protected Document createDefaultModel() {
            return new IntDocument();
        }

        static class IntDocument extends PlainDocument {

            public void insertString(int offs, String str, AttributeSet a)
                    throws BadLocationException {

                if(str == null) {
                    return;
                }
                char[] intString = str.toCharArray();
                char[] result = new char[intString.length];

                int j = 0;
                for(int i = 0; i < intString.length; i++) {
                    if ((intString[i] > 47 && intString[i] < 58) || (intString[i] == 8)) {
                        result[j++] = intString[i];
                    } else if (j == 0 && intString[i] == 45) {
                        //Allow minus sign in the beginning
                        result[j++] = intString[i];
                    }
                }
                super.insertString(offs, new String(result,0,j), a);
            }
        }
    }